using System;
using System.IO;
using System.Text.Json;
using System.Windows;
using Microsoft.Extensions.Logging;

namespace DocumentCreationSystem.Services
{
    /// <summary>
    /// 窗口设置服务 - 保存和恢复窗口位置、大小等设置
    /// </summary>
    public class WindowSettingsService
    {
        private readonly ILogger<WindowSettingsService> _logger;
        private readonly string _settingsDirectory;
        private readonly string _settingsFilePath;

        public WindowSettingsService(ILogger<WindowSettingsService> logger)
        {
            _logger = logger;
            _settingsDirectory = Path.Combine(
                Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
                "DocumentCreationSystem",
                "WindowSettings");
            _settingsFilePath = Path.Combine(_settingsDirectory, "window-settings.json");
            
            // 确保设置目录存在
            Directory.CreateDirectory(_settingsDirectory);
        }

        /// <summary>
        /// 保存窗口设置
        /// </summary>
        public void SaveWindowSettings(string windowName, WindowSettings settings)
        {
            try
            {
                var allSettings = LoadAllSettings();
                allSettings[windowName] = settings;

                var json = JsonSerializer.Serialize(allSettings, new JsonSerializerOptions
                {
                    WriteIndented = true,
                    Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
                });

                File.WriteAllText(_settingsFilePath, json);
                _logger.LogDebug($"已保存窗口设置: {windowName}");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"保存窗口设置失败: {windowName}");
            }
        }

        /// <summary>
        /// 加载窗口设置
        /// </summary>
        public WindowSettings? LoadWindowSettings(string windowName)
        {
            try
            {
                var allSettings = LoadAllSettings();
                if (allSettings.TryGetValue(windowName, out var settings))
                {
                    _logger.LogDebug($"已加载窗口设置: {windowName}");
                    return settings;
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"加载窗口设置失败: {windowName}");
            }

            return null;
        }

        /// <summary>
        /// 应用窗口设置到窗口
        /// </summary>
        public void ApplyWindowSettings(Window window, string windowName)
        {
            try
            {
                var settings = LoadWindowSettings(windowName);
                if (settings == null) return;

                // 验证位置是否在有效屏幕范围内
                if (IsPositionValid(settings.Left, settings.Top, settings.Width, settings.Height))
                {
                    window.Left = settings.Left;
                    window.Top = settings.Top;
                    window.Width = settings.Width;
                    window.Height = settings.Height;

                    if (settings.WindowState != WindowState.Minimized)
                    {
                        window.WindowState = settings.WindowState;
                    }

                    _logger.LogDebug($"已应用窗口设置: {windowName}");
                }
                else
                {
                    _logger.LogWarning($"窗口设置位置无效，使用默认位置: {windowName}");
                    SetDefaultPosition(window);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"应用窗口设置失败: {windowName}");
                SetDefaultPosition(window);
            }
        }

        /// <summary>
        /// 从窗口保存设置
        /// </summary>
        public void SaveFromWindow(Window window, string windowName)
        {
            try
            {
                var settings = new WindowSettings
                {
                    Left = window.Left,
                    Top = window.Top,
                    Width = window.Width,
                    Height = window.Height,
                    WindowState = window.WindowState,
                    LastSaved = DateTime.Now
                };

                SaveWindowSettings(windowName, settings);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"从窗口保存设置失败: {windowName}");
            }
        }

        /// <summary>
        /// 验证位置是否有效
        /// </summary>
        private bool IsPositionValid(double left, double top, double width, double height)
        {
            try
            {
                // 检查是否在任何屏幕的工作区域内
                var workingArea = SystemParameters.WorkArea;
                var virtualScreenLeft = SystemParameters.VirtualScreenLeft;
                var virtualScreenTop = SystemParameters.VirtualScreenTop;
                var virtualScreenWidth = SystemParameters.VirtualScreenWidth;
                var virtualScreenHeight = SystemParameters.VirtualScreenHeight;

                // 窗口至少要有一部分在屏幕内
                var windowRight = left + width;
                var windowBottom = top + height;

                return left < virtualScreenLeft + virtualScreenWidth &&
                       windowRight > virtualScreenLeft &&
                       top < virtualScreenTop + virtualScreenHeight &&
                       windowBottom > virtualScreenTop &&
                       width > 100 && height > 100; // 最小尺寸检查
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 设置默认位置
        /// </summary>
        private void SetDefaultPosition(Window window)
        {
            try
            {
                var workingArea = SystemParameters.WorkArea;
                window.Left = workingArea.Right - window.Width - 20;
                window.Top = workingArea.Top + 20;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "设置默认窗口位置失败");
            }
        }

        /// <summary>
        /// 加载所有设置
        /// </summary>
        private Dictionary<string, WindowSettings> LoadAllSettings()
        {
            try
            {
                if (File.Exists(_settingsFilePath))
                {
                    var json = File.ReadAllText(_settingsFilePath);
                    return JsonSerializer.Deserialize<Dictionary<string, WindowSettings>>(json) 
                           ?? new Dictionary<string, WindowSettings>();
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "加载窗口设置文件失败");
            }

            return new Dictionary<string, WindowSettings>();
        }
    }

    /// <summary>
    /// 窗口设置数据模型
    /// </summary>
    public class WindowSettings
    {
        public double Left { get; set; }
        public double Top { get; set; }
        public double Width { get; set; }
        public double Height { get; set; }
        public WindowState WindowState { get; set; } = WindowState.Normal;
        public DateTime LastSaved { get; set; } = DateTime.Now;
    }
}
